import subprocess
import os

def read_package_names(file_path):
    if not os.path.exists(file_path):
        print(f"错误：文件'{file_path}'不存在。")
        return []

    package_names = []
    with open(file_path, 'r') as file:
        for line in file:
            # 去掉行末的换行符，然后按空格分割
            names = line.strip().split()
            package_names.extend(names)  # 添加到包名列表中

    # 去除空字符串
    package_names = [name for name in package_names if name]

    if not package_names:
        print("错误：文件中没有有效的包名。")
    
    return package_names

def download_packages(package_names):
    # 创建 package 文件夹，如果不存在的话
    download_dir = 'package'
    os.makedirs(download_dir, exist_ok=True)
    
    for package in package_names:
        print(f"正在下载包: {package}")
        subprocess.run(['pip', 'download', package, '-d', download_dir])

if __name__ == "__main__":
    # 指定你的packages.cfg文件路径
    packages_file = 'packages.cfg'
    
    # 读取包名
    packages = read_package_names(packages_file)
    
    # 如果有有效的包名，则下载
    if packages:
        download_packages(packages)